#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:

"""
@version: 1.0
@author: readerror
@contact: readerror@readerror.cn
@contact1: readerror000@gmail.com
@site: http://www.readerror.cn
@software: PyCharm
@file: example.py
@time: 2017/3/6 15:42
"""

import threading
import time

from pprint import pprint

from zstack import Client
from zstack import controller as zstack_osyl

VM_COUNT = 1
NETWORK_COUNT = 1
ADMIN_USERNAME = 'admin'
ADMIN_PASSWORD = 'password'
# ZSTACK_API_URL = 'http://202.127.28.209:7080/zstackstrong/api'
# ZSTACK_API_URL = 'http://202.127.28.209:7080/zstack/api'
ZSTACK_API_URL = 'http://192.168.1.115:8080/zstack/api'
ZSTACK_NET_SERVICES = None
CLUSTER_UUID = None
ZONE_UUID = None

resource_uuid = 'cc194032902848bc897cc755d83bb219'  # 测试用云路由规格
INSTANCE_OFFERING_UUID = '30eeca8e034c4109affee3ae090973ca'
IMAGE_UUID = 'd08a69706d81457fadddbb4fa6ec175e'
NIC = 'enp3s0'


def test_n1(_client):
    # 建立网络
    for i in range(210, 211):
        _client.osyl_create_network('l21', '.'.join([str(i)] * 3) + '.0/24', NIC)


def test_nx_vmx_1(_client, network_mutex):
    # 逐个建立网络和虚拟机
    jobs = []
    for i in range(200, 200 + NETWORK_COUNT):
        print(i, time.time() - time_start)
        l3_network_uuid = zstack_osyl.network.create_network(
            client, network_mutex, u'test' + str(i), '200.' + '.'.join([str(i)] * 2) + '.0/24', NIC,
            'Flat',
            # 'vrouter', resource_uuid=resource_uuid,
            services=ZSTACK_NET_SERVICES,
            cluster_uuid=CLUSTER_UUID,
            zone_uuid=ZONE_UUID
        )
        for _ in range(VM_COUNT):
            jobs.append(zstack_osyl.vm.create_vm_instance(
                client, 'test1', l3_network_uuid, IMAGE_UUID, INSTANCE_OFFERING_UUID, async=True).get('job').get(
                'uuid'))

    print('network ok vm starting  ', time.time() - time_start)
    print(jobs)

    for i, job in enumerate(jobs):
        _client.wait_mission_complete(job)
        print('vm ', i + 1, job, time.time() - time_start)

    print('end  ', time.time() - time_start)


def test_nx_vmx_2(_client, network_mutex):
    # 建立网络
    jobs = []
    l3_networks_uuid = []
    for i in range(200, 200 + NETWORK_COUNT):
        print(i, time.time() - time_start)
        l3_networks_uuid.append(
            zstack_osyl.network.create_network(
                client, network_mutex, u'test' + str(i), '200.' + '.'.join([str(i)] * 2) + '.0/24', NIC,
                'Flat',
                # 'vrouter', resource_uuid=resource_uuid,
                services=ZSTACK_NET_SERVICES,
                cluster_uuid=CLUSTER_UUID,
                zone_uuid=ZONE_UUID, async=True)
        )

    # 建立网络下虚拟机
    for l3_network_uuid in l3_networks_uuid:
        for _ in range(VM_COUNT):
            jobs.append(zstack_osyl.vm.create_vm_instance(
                client, 'test1', l3_network_uuid, IMAGE_UUID, INSTANCE_OFFERING_UUID, async=True
                ).get('job').get('uuid'))

    print('network ok vm starting ', time.time() - time_start)
    print(jobs)

    for i, job in enumerate(jobs):
        _client.wait_mission_complete(job)
        print('vm ', i + 1, job, time.time() - time_start)

    print('end  ', time.time() - time_start)


if __name__ == '__main__':
    time_start = time.time()
    client = Client(ADMIN_USERNAME, ADMIN_PASSWORD, ZSTACK_API_URL)
    client.login()
    # if not ZSTACK_NET_SERVICES or not CLUSTER_UUID or not ZONE_UUID:
    #     config = zstack_osyl.system.environment_variables_init(client)
    #     ZSTACK_NET_SERVICES = config.get('services')
    #     CLUSTER_UUID = config.get('cluster_uuid')
    #     ZONE_UUID = config.get('zone_uuid')

    # 查询全部镜像
    # client.osyl_query_image()
    # 查询指定uuid的镜像详细信息
    # client.osyl_query_image_by_uuid('3a8506cbb26c4b3d838d7d29ec73aed6')
    # 删除指定镜像
    # client.osyl_delete_image('3a8506cbb26c4b3d838d7d29ec73aed6')

    # 查询镜像服务器
    # client.osyl_query_backup_storage()

    # 添加镜像
    # client.osyl_add_image('py_test111111111111', 'py_description', 'RootVolumeTemplate', 'Linux',
    #                       'http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-server-i386.iso',
    #                       ['48a1019169004434a78968d18dc09000'], 'qcow2')
    # 更新镜像
    # client.osyl_update_image('4e1069d515b24ee29c4effe2b8f4feae', 'py_name_test', 'py_description_test')

    # 查询用户标签
    # client.osyl_query_user_tag('b30fff0ee72945f7a3236a1fbd219bea')
    # 添加用户标签
    # client.osyl_create_user_tag('b30fff0ee72945f7a3236a1fbd219bea', 'rrrrrrrrrrrrrrrrrrrrrr')
    # 删除标签
    # client.osyl_delete_tag('27bcb5b2896749b2bd79b2254df3e402')

    # 创建安全组
    # client.osyl_create_security_group('py_name_security_group', 'py_description_security_group')
    # 安全组规则添加
    # client.osyl_add_security_group_rule('Ingress', 'TCP', 80, 80, '757aba47ad1d457f8f38bb5012d359a6')

    # 查询l3网络
    # client.osyl_query_l3_network()
    # 添加安全组到l3网络
    # client.osyl_attach_security_group_to_l3_network(
    # 'c88169cc00864306b00becf33b9d7f20', '757aba47ad1d457f8f38bb5012d359a6')

    # 创建账户
    # client.osyl_create_account('py_account1', 'password', async=True)
    # 删除账户
    # client.osyl_delete_account('59e087ab648840c49ebddd0d7b02ed80', async=True)
    # 修改密码
    # client.osyl_update_account('83afd851b07e4b729d215300b7bb60dd', 'passwordNew', async=True)

    # 销毁虚拟机
    # client.osyl_destroy_vm_instance('95cf328aaf3a4c0db9edef58a392c34a', async=True)
    # 销毁网络
    # client.osyl_destroy_l2_network('500af9bdcb954220a9d10b2dfb727fff', async=True)

    net_mutex = threading.Lock()
    # 逐个建立网络和虚拟机
    test_nx_vmx_1(client, net_mutex)
    # 并行创建网络虚拟机
    # test_nx_vmx_2(client, net_mutex)

    # 查询任务
    # print client.query_mission('0b766f4986934c81a96dfade47e5f793')

    # 查询L3网
    # print client.query_l3_network(details=False)

    # client.osyl_get_eip4vm('c88169cc00864306b00becf33b9d7f20', 'ebe45031041940f1a636c614e1939ae0')

    # 创建镜像标签
    # client.osyl_updata_image_category(IMAGE_UUID, ['sdfsdfsdf', 'htygtyg', {'complex': 'XXXX'}])
    # print(client.osyl_query_image_property(IMAGE_UUID))

    # client.osyl_updata_image_category(IMAGE_UUID, ['1234'])
    # print(client.osyl_query_image_property(IMAGE_UUID))

    # pprint(zstack_osyl.vm.query_vm_instance_by_username(client, 'admin'))
    # pprint(zstack_osyl.system.query_backup_storage(client))
